import postcssConfig from '../../../postcss.config.js';

var config = {
  viewportWidth: 320,
  viewportHeight: 568, // not now used; TODO: need for different units and math for different properties
  unitPrecision: 5,
  viewportUnit: 'vw',
  minPixelValue: 1,
};


if (postcssConfig.plugins && postcssConfig.plugins['postcss-px-to-viewport'] && postcssConfig.plugins['postcss-px-to-viewport'].viewportWidth) {
  config.viewportWidth = postcssConfig.plugins['postcss-px-to-viewport'].viewportWidth;
}

if (postcssConfig.plugins && postcssConfig.plugins['postcss-px-to-viewport'] && postcssConfig.plugins['postcss-px-to-viewport'].viewportHeight) {
  config.viewportHeight = postcssConfig.plugins['postcss-px-to-viewport'].viewportHeight;
}

if (postcssConfig.plugins && postcssConfig.plugins['postcss-px-to-viewport'] && postcssConfig.plugins['postcss-px-to-viewport'].unitPrecision) {
  config.unitPrecision = postcssConfig.plugins['postcss-px-to-viewport'].unitPrecision;
}

if (postcssConfig.plugins && postcssConfig.plugins['postcss-px-to-viewport'] && postcssConfig.plugins['postcss-px-to-viewport'].unitPrecision) {
  config.unitPrecision = postcssConfig.plugins['postcss-px-to-viewport'].unitPrecision;
}

if (postcssConfig.plugins && postcssConfig.plugins['postcss-px-to-viewport'] && postcssConfig.plugins['postcss-px-to-viewport'].minPixelValue) {
  config.minPixelValue = postcssConfig.plugins['postcss-px-to-viewport'].minPixelValue;
}



function createPxReplace(pixels, viewportSize, minPixelValue, unitPrecision, viewportUnit) {
    var pixels = parseFloat(pixels);
    if (pixels <= minPixelValue) {
      pixels = minPixelValue;
    }
    return toFixed((pixels / viewportSize * 100), unitPrecision) + viewportUnit;
  
}

function toFixed(number, precision) {
  var multiplier = Math.pow(10, precision + 1),
    wholeNumber = Math.floor(number * multiplier);
  return Math.round(wholeNumber / 10) * 10 / multiplier;
}



export default function(pixels) {

  return createPxReplace(pixels, config.viewportWidth, config.minPixelValue, config.unitPrecision, config.viewportUnit);

}
